<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <SmForm
      class="-mb-15px"
      ref="formRef"
      isCol
      label-width="150px"
      v-model="formData"
      v-loading="formLoading"
      :options="requestFormOptions"
      :getModelValue="getFormData"
    >
      <template #files>
        <FileUpload
          v-model="formData.fileList"
          @update:model-value="(val) => changeFilesData(val, formData, 'files')"
        />
      </template>
    </SmForm>

    <template #footer>
      <el-button @click="submitFormDB" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { createUser, getRoleList, getUser, updateUser } from "@/api/user";
import { addProperty } from "@/components/SmForm/src/utils";
import { createDBFn } from "@/utils/decorate";
import { defaultProps } from "@/utils/tree";
import {
  getDeptTree,
  getOrganizationList,
  getProvinceCityDistrictList,
  getUserList,
} from "@/commonData";
import { businessStatusList, enableList } from "@/commonData/dict";
import DeptAPI from "@/api/system/dept-api";
import { changeFilesData } from "@/utils/changeData";
import OrgAPI from "@/api/org/org";

/** 仓库 表单 */
defineOptions({ name: "OpenForm" });

const { t } = useI18n(); // 国际化

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(""); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(""); // 表单的类型：create - 新增；update - 修改
const initFormData = () => {
  return {};
};
const formData: any = ref(initFormData());
const formRef = ref(); // 表单 Ref
const organizationList = ref([]);

const { provinceList, cityList, districtList, changeCity, changeProvince } =
  getProvinceCityDistrictList(formData, formRef);

/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true;
  dialogTitle.value = t("action." + type);
  formType.value = type;
  resetForm();

  getOrganizationList(organizationList);

  if (type === "create") {
    formData.value.parentId = id;
    return;
  }
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await OrgAPI.getFormData(id);
      // 主动触发表单数据回显
      formRef.value.initForm();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(["success"]); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value as unknown as any;
    if (formType.value === "create") {
      await OrgAPI.create(data);
    } else if (formType.value === "update") {
      await OrgAPI.update(data.id, data);
    }
    ElMessage.success("操作成功");
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit("success");
  } finally {
    formLoading.value = false;
  }
};
const submitFormDB = createDBFn(submitForm);

/** 重置表单 */
const resetForm = () => {
  formData.value = initFormData();
  formRef.value?.resetFields();
};

const requestFormOptions: any = ref([]);
const createRequestFormOptions = () => {
  // {
  //   id: "string", //机构ID: 	uuid
  //   organizationName: "string", //机构名称-1
  //   organizationNo: "string", //机构编码-1
  //   organizationShortName: "string", //机构简称-1
  //   parentId: "string", //上级机构ID
  //   areaCode: "string", //区号-1
  //   province: "string", //省-1
  //   city: "string", // 市-1
  //   district: "string", //区-1
  //   address: "string", //机构所在地址-1
  //   phone: "string", //机构电话-1
  //   fax: "string", //机构传真-1-
  //   establishDate: "string", //成立日期-1
  //   isLegalPerson: 0, //是否是法人机构：是1，否0-1
  //   hasAmountViewPermission: 0, //自主结算资格：是1，否0-1
  //   hasSettlementQualification: 0, //可视实收金额权限： 是1，否0-1
  //   businessStatus: 0, // 业务状态：1-正常，2-停业，3-注销-1
  //   files: "string", //机构资料文件- 文件上传到时候得看下-插槽
  //   remark: "string", //备注-1
  // };

  // files: "string", //机构资料文件- 文件上传到时候得看下-插槽

  const list = [
    // requiredFlag: true,必填项后面再弄
    {
      type: "input",
      label: "机构名称",
      prop: "organizationName",
      placeholder: "机构名称",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "机构编码",
      prop: "organizationNo",
      placeholder: "机构编码",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "机构简称",
      prop: "organizationShortName",
      placeholder: "机构简称",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },

    {
      type: "tree-select",
      placeholder: "上级机构",
      prop: "parentId",
      label: "上级机构",
      attrs: {
        filterable: true,
        clearable: true,
        data: organizationList,
        // props: defaultProps,
        "check-strictly": true,
        // "node-key": "id", //默认是vvalue
      },
    },
    {
      type: "input",
      label: "区号",
      prop: "areaCode",
      placeholder: "区号",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "select",
      placeholder: "省",
      prop: "province",
      label: "省",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
        onChange: changeProvince,
      },
      children: provinceList,
    },
    {
      type: "select",
      placeholder: "市",
      prop: "city",
      label: "市",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
        onChange: changeCity,
      },
      children: cityList,
    },
    {
      type: "select",
      placeholder: "区",
      prop: "district",
      label: "区",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: districtList,
    },

    {
      type: "input",
      label: "机构所在地址",
      prop: "address",
      placeholder: "机构所在地址",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "机构电话",
      prop: "phone",
      placeholder: "机构电话",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "input",
      label: "机构传真",
      prop: "fax",
      placeholder: "机构传真",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    {
      type: "date-picker",
      placeholder: "成立日期",
      prop: "establishDate",
      label: "成立日期",
      attrs: {
        clearable: true,
        type: "date",
        "range-separator": "~",
        editable: false,
        "value-format": "YYYY-MM-DD",
      },
    },

    {
      type: "select",
      placeholder: "法人机构",
      prop: "isLegalPerson",
      label: "法人机构",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: enableList,
    },
    {
      type: "select",
      placeholder: "自主结算资格",
      prop: "hasAmountViewPermission",
      label: "自主结算资格",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: enableList,
    },
    {
      type: "select",
      placeholder: "可视实收金额权限",
      prop: "hasSettlementQualification",
      label: "可视实收金额权限",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: enableList,
    },
    {
      type: "select",
      placeholder: "业务状态",
      prop: "businessStatus",
      label: "业务状态",
      attrs: {
        filterable: true,
        clearable: true,
        style: {
          width: "100%",
        },
      },
      children: businessStatusList,
    },
    {
      type: "input",
      label: "主营业务范围",
      prop: "businessScope",
      placeholder: "主营业务范围",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
    //files: "string", //机构资料文件- 文件上传到时候得看下-插槽
    {
      slot: "files",
      label: "机构资料文件",
    },
    {
      type: "input",
      label: "备注",
      prop: "remark",
      placeholder: "备注",
      attrs: {
        style: { width: "100%" },
        clearable: true,
      },
    },
  ];

  addProperty(list);
  return list;
};
requestFormOptions.value = createRequestFormOptions();

const getFormData = () => {
  return formData.value;
};
</script>
